package com.qf.service.impl;

import com.qf.bean.User;
import com.qf.dao.UserDao;
import com.qf.service.UserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @author yao
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    //1. 校验用户名是否可用.
    @Override
    public Integer checkUsername(String username) {
        // 健壮性判断,避免username为空串.
        if (StringUtils.isEmpty(username)){
            // trim()的作用是去掉字符串两端的多余的空格
            username = username.trim();
        }
        // 调用dao查询条数.
        Integer count = userDao.findCountByUsername(username);
        // 返回数据
        return count;
    }

    // 2.注册账号
    @Override
    @Transactional
    public Integer register(User user) {
        //1. 给密码加密.并设置到user里.
        user.setPassword(new Md5Hash(user.getPassword()).toString());
        //2. 调用dao保存
        return userDao.save(user);
    }

    // 3.执行登录
    @Override
    public User login(String username, String password) {
        //1. 调用dao根据用户查询用户信息.
        User user = userDao.findByUsername(username);
        //2. 判断用户名是否正确.
        if(user != null) {
            //3. 判断密码是否正确.
            if(user.getPassword().equals(new Md5Hash(password).toString())){
                // 用户名和密码都正确.
                return user;
            }
        }
        // 用户名或密码错误
        return null;
    }
}
